package com.test.sdk.core.exception;

import com.test.sdk.common.exception.SdkException;
import com.test.sdk.common.util.ErrorCodeTO;
import com.test.sdk.common.util.ErrorConstants;
import com.test.sdk.common.util.JsonUtil;
import com.test.sdk.common.util.ResponseTO;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 徒有琴
 */
@Component
public class SdkExceptionHandler implements HandlerExceptionResolver {
    @Override
    @Nullable
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {
        e.printStackTrace();
//        ResponseTO response = new ResponseTO();
//        response.setSuccess(false);
//        if (e instanceof SdkException) {
//            SdkException exception = (SdkException) e;
//            response.setError(exception.getError());
//        }else{
//            response.setError(ErrorConstants.UNKNOWN_ERROR);
//        }
//        MappingJackson2JsonView view=new MappingJackson2JsonView();
//        view.setExtractValueFromSingleKeyModel(true);
//        return new ModelAndView(view,"response",response);
        handler(httpServletResponse,e);
        return null;
    }

    public static void handler(HttpServletResponse httpServletResponse, Exception e) {

        PrintWriter out = null;
        try {
            ResponseTO result = new ResponseTO();
            result.setSuccess(false);//本次失败
            if (e instanceof SdkException) {
                SdkException exception = (SdkException) e;
                ErrorCodeTO code = exception.getError();
                result.setError(code);
            }
            String json = JsonUtil.getJSON(result);
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.setHeader("Cache-Control", "no-cache");
            httpServletResponse.setContentType("application/json; charset=UTF-8");
            out = httpServletResponse.getWriter();
            out.write(json);
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
